/*
 * @Author: your name
 * @Date: 2022-02-10 16:23:52
 * @LastEditTime: 2022-02-12 09:44:34
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \jike\src\utils\request.js
 */
import axios from 'axios';
import { getToken, removeToken } from 'utils/storage';
import history from 'utils/history';
import { message } from 'antd';
export const baseURL = 'http://geek.itheima.net';
const instance = axios.create({
  baseURL: baseURL,
  timeout: 5000,
});

// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    const token = getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response.data;
  },
  function (error) {
    console.dir(error.response);
    if (error.response.status === 401) {
      // token过期
      removeToken();
      // 跳转到登录页
      history.push('/login');
      message.warning('用户信息已过期');
    }
    return Promise.reject(error);
  }
);

export default instance;
